import React, {createContext, useContext, useEffect, useReducer, useState} from "react";
import poetry1aItems from './data/1a.json'
import {poetryData} from "./helpers/poetryData";
import {AppToaster} from './helpers/Toaster'
import {Intent} from "@blueprintjs/core/lib/cjs/common/intent";
import {getFavorites, getErrorsInRange, getCounter, saveCounter} from "./helpers/storage";
import {generateQuestion} from "./helpers/question.js";

const PoetryContext = createContext(false);
export const usePoetry = () => useContext(PoetryContext);

export const PoetryProvider = ({children}) => {
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [onlyFavorite, toggleOnlyFavorite] = useReducer(v => {
        //从全部切换收藏, 当前的selectedIndex可能不存在
        if (!v) {
            setSelectedIndex(0);
        }
        return !v;
    }, false);
    const [favoriteUpdater, toggleFavoriteUpdater] = useReducer(v => !v, true);
    const [keyboard, toggleKeyboard] = useReducer(v => !v, false);
    const [errorRange, setErrorRange] = useState(1);
    const [nextKey, setNextKey] = useState(false);
    const [counter, updateCounter] = useState(getCounter);
    const [userWeak] = getErrorsInRange(errorRange);
    const [poetryItems, setPoetryItems] = useState(poetry1aItems);
    const [playQueue, setPlayQueue] = useState([]);
    const [showPinyin, togglePinyin] = useReducer(v => !v, true);
    const [weakTip, toggleWeakTip] = useReducer(v => !v, false);
    const [showTone, toggleTone] = useReducer(v => !v, true);
    const [trainFromError, toggleTrainFromError] = useReducer(v => !v, false);
    const [showTable, toggleTable] = useReducer(v => !v, true);
    const poetry = poetryItems[selectedIndex];
    const [questionIndex] = useState(0);
    const questions = generateQuestion(poetry, trainFromError, userWeak);
    const question = questions[questionIndex];
    const nextIndex = selectedIndex < poetryItems.length - 1 ? selectedIndex + 1 : 0;
    const threeDaysWeak = errorRange === 3 ? userWeak : getErrorsInRange(3)[0];
    // 没有问题换下一首, 发生在弱项修正模式
    if (!question) {
        setSelectedIndex(nextIndex);
    }
    const trainFromErrorDisabled = (Object.keys(userWeak).length === 0);
    const goNext = (rightLength) => {
        if (questions.length === rightLength) {
            const {trained, stronger} = counter;
            if (!showPinyin) {
                updateCounter({
                    trained: counter.trained + 1,
                    stronger
                });
            } else {
                updateCounter({
                    trained,
                    stronger: stronger + 1
                });
            }
            setSelectedIndex(nextIndex);
            if(!showPinyin) {
                toggleWeakTip();
            }
        } else {
            AppToaster.show({
                message: `${questions.length - rightLength} 处错误未完成或有错误.`,
                intent: Intent.WARNING,
                icon: "hand"
            });
        }
    };
    const resetCounter = () => {
        updateCounter({
            trained: 0,
            stronger: 0,
        });
    };
    const favorites = getFavorites();

    useEffect(() => {
        poetryData.then(v => {
            if (onlyFavorite) {
                setPoetryItems(v.filter(v => favorites.includes(v.title)));
            } else {
                setPoetryItems(v)
            }
        });
    }, [onlyFavorite, favoriteUpdater, favorites]);


    useEffect(() => {
       saveCounter(counter);
    }, [counter]);

    const addPlayItem = (item) => {
      setPlayQueue(Array.isArray(item) ? item: [item])
    };

    return (
        <PoetryContext.Provider value={{
            errorRange,
            setErrorRange,
            favorites,
            onlyFavorite,
            toggleOnlyFavorite,
            toggleFavoriteUpdater,
            showTable,
            toggleTable,
            poetry,
            showPinyin,
            togglePinyin,
            showTone,
            toggleTone,
            trainFromError,
            toggleTrainFromError,
            poetryItems,
            selectedIndex,
            setSelectedIndex,
            question,
            goNext,
            userWeak,
            trainFromErrorDisabled,
            counter,
            resetCounter,
            playQueue,
            setPlayQueue,
            addPlayItem,
            weakTip,
            toggleWeakTip,
            threeDaysWeak,
            nextKey,
            setNextKey,
            keyboard,
            toggleKeyboard
        }}>
            {children}
        </PoetryContext.Provider>
    );
};
